package com.king.oa.view.action;

import java.util.Date;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.king.oa.base.BaseAction;
import com.king.oa.domain.Forum;
import com.king.oa.domain.Reply;
import com.king.oa.domain.Topic;
import com.king.oa.util.QueryHelper;
import com.opensymphony.xwork2.ActionContext;

@Controller
@Scope("prototype")
public class TopicAction extends BaseAction<Topic> {

	private static final long serialVersionUID = 8888682440420653516L;

	private Long forumId;
	
	/** 显示单个主题(主贴+回帖列表) */
	public String show() throws Exception{
		//准备数据: topic
		Topic topic = topicService.findById(model.getId());
		ActionContext.getContext().put("topic", topic);
		
//		//准备数据： replyList
//		List<Reply> replyList = replyService.findByTopic(topic);
//		ActionContext.getContext().put("replyList", replyList);
		
//		//准备分页信息v1
//		PageBean pageBean = replyService.findPageBeanByTopic(pageNum, pageSize, topic);
//		ActionContext.getContext().getValueStack().push(pageBean);
		
//		//准备分页信息v2
//		String hql = "FROM Reply r WHERE r.topic=? ORDER BY r.postTime ASC";
//		List<Object> parameters = new ArrayList<>();
//		parameters.add(topic);
//		
//		PageBean pageBean = replyService.findPageBean(pageNum, pageSize, hql, parameters);
//		ActionContext.getContext().getValueStack().push(pageBean);
		
		//准备分页信息v3
		new QueryHelper(Reply.class, "r")//
				.addCondition("r.topic=?", topic)//
				.addOrderByProperty("r.postTime", true)
				.prepaerePageBean(replyService, pageNum, pageSize);
		
		
		return "show";
	}
	
	/** 发表新主题页面 */
	public String addUI() throws Exception {
		//准备数据
		Forum forum = forumService.findById(forumId);
		ActionContext.getContext().put("forum", forum);
		
		
		return "addUI";
	}

	
	/** 发表新主题 */
	public String add() throws Exception {
		//封装基本属性
		
		// >> 表单数据，已封装了title，content
//		model.setTitle(title);
//		model.setContent(content);
		model.setForum(forumService.findById(forumId));
		// >> 当前直接获取的信息
		System.out.println(getCurrentUser().getName());
		model.setAuthor(getCurrentUser());// 当前登录用户
		model.setIpAddr(ServletActionContext.getRequest().getRemoteAddr()); // 当前请求的IP
		model.setPostTime(new Date()); // 当前时间
		
		//保存到数据库
		topicService.save(model);
		
		return "toShow";//发表新主题后转到新主题的显示页面
	}
	
	
	
	/** 删除 */
	public String delete() throws Exception {
		return "show";
	}

	/** 修改页面 */
	public String editUI() throws Exception {
		return "saveUI";
	}

	/** 修改 */
	public String edit() throws Exception {
		return "toList";
	}
	
	public Long getForumId() {
		return forumId;
	}

	public void setForumId(Long forumId) {
		this.forumId = forumId;
	}
	
}
